package com.me.TextMissed_a1;


import java.util.Locale;

import com.me.TextMissed_a1.MyAppWidget;

import android.app.Activity;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.FontMetricsInt;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.Toast;

public class MyAppWidget extends AppWidgetProvider {
	
	private Toast toast;	
	public static final String UPDATE_ONDEMAND = "com.me.TextMissed_a1.UPDATE_ONDEMAND";
	public static final String UPDATE_PREFERENCE = "com.me.TextMissed_a1.UPDATE_PREFERENCE";
	private static final String ImageButton = null;

	
	//Automatic updater
	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
		Log.d("_TextMissed_a1_", "++++++++++++++Widget onUpdate ");
		super.onUpdate(context, appWidgetManager, appWidgetIds);
		
		//get configuration language
		Configuration config = context.getResources().getConfiguration();
		Locale.getDefault();
		Log.d("_TextMissed_a1_", "++++++++++++++Widget onUpdate Configuration config AFTER: "+config.locale);
		
		for (int i = 0; i < appWidgetIds.length; i++) {
			int appWidgetId = appWidgetIds[i];
			//Get RemoteViews
			RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
			
			//Update layout
			updateWidgetLayout(views, context);
			
	        
			 // Klik do otwarcia wiadomosci sms
	        Intent intent = new Intent();
	        intent.setAction(WidgetReceiver.WIDGET_INTENT_SMS);
	        intent.setClassName(WidgetReceiver.class.getPackage().getName(), WidgetReceiver.class.getName());

	        PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
	        views.setOnClickPendingIntent(R.id.tvWidgetText1, pendingIntent);
	        //views.setOnClickPendingIntent(R.id.tvWidgetText2, pendingIntent);
	        

	        // Klik do otwarcia rejestru nie odebranych polaczen
	        intent.setAction(WidgetReceiver.WIDGET_INTENT_CALL);
	        intent.setClassName(WidgetReceiver.class.getPackage().getName(), WidgetReceiver.class.getName());

	        PendingIntent pendingIntentCall = PendingIntent.getBroadcast(context.getApplicationContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
	        //views.setOnClickPendingIntent(R.id.tvWidgetText3, pendingIntentCall);
	        //views.setOnClickPendingIntent(R.id.tvWidgetText4, pendingIntentCall);		
			
			
			//update widget
			appWidgetManager.updateAppWidget(appWidgetId, views);	
		}
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		//Log.d("_TextMissed_a1_", "++++++++++++++Widget onReceive "+ context.getString(R.string.tvWidgetText1));
		super.onReceive(context, intent);
		
		if(intent.getAction().equals(UPDATE_ONDEMAND)) {
			String myTextSMS = intent.getStringExtra("WidgetTextSMS");
			String myTextCall = intent.getStringExtra("WidgetTextCALL");
			
			updateWidget(context, myTextSMS, myTextCall);
			Log.d("_TextMissed_a1_", "Widget onReceive SMS "+ myTextSMS+" - "+intent.getStringExtra("WidgetTextSMS"));
			Log.d("_TextMissed_a1_", "Widget onReceive Call "+ myTextCall+" - "+intent.getStringExtra("WidgetTextCALL"));
		}
		
		if(intent.getAction().equals(UPDATE_PREFERENCE)) { //update preference
			updateWidgetLanguage(context);
		}
	}	
	
	
	//On demand language updater
	public void updateWidgetLanguage(Context context) {
		//get configuration language
		Locale.getDefault();		
				
		//Get AppWidgetManager
		AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
		//Get widget IDs
		ComponentName thisWidged = new ComponentName(context, MyAppWidget.class);
		int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisWidged);
		//Update all widget copies
		for (int i = 0; i < appWidgetIds.length; i++) {
			int appWidgetId = appWidgetIds[i];
			//Get RemoteViews
			RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
	
			//Update layout
			updateWidgetLayout(views, context);
			//Save changes
			appWidgetManager.updateAppWidget(appWidgetId, views);
		}		
	}
	
	//updateWidgetLayout after changes
	private void updateWidgetLayout(RemoteViews views, Context context){
		//views.setTextViewText(R.id.tvWidgetText1, context.getString(R.string.tvWidgetText1));
		
		String text = context.getString(R.string.tvWidgetText1); 		 
        Paint  mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setTextSize(10);
        mPaint.setColor(0xffffffff);
        mPaint.setTypeface(Typeface.create(Typeface.SERIF, Typeface.BOLD));
        float w = mPaint.measureText(text, 0, text.length());
        int olo = (int) w;
        // Create an empty, mutable bitmap
		Bitmap bitmap = Bitmap.createBitmap(olo, 13+5, Bitmap.Config.ARGB_4444);
		// get a canvas to paint over the bitmap
		Canvas canvas = new Canvas(bitmap);
		bitmap.eraseColor(0);
		canvas.drawText(context.getString(R.string.tvWidgetText1), 0,15, mPaint);
		
		views.setImageViewBitmap(R.id.tvWidgetText1, bitmap);
		//views.setTextViewText(R.id.tvWidgetText3, context.getString(R.string.tvWidgetText3));		
	}
	
	//On demand updater
	public void updateWidget(Context context, String myTextSMS, String myTextCall) {
		//get configuration language
		Locale.getDefault();
		
		//Get AppWidgetManager
		AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
		//Get widget IDs
		ComponentName thisWidged = new ComponentName(context, MyAppWidget.class);
		int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisWidged);
		//Update all widget copies
		for (int i = 0; i < appWidgetIds.length; i++) {
			int appWidgetId = appWidgetIds[i];
			//Get RemoteViews
			RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
			
			
			
			// When intents are compared, the extras are ignored, so we need to embed the extras
            // into the data so that the extras will not be ignored.
            //intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
            //RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.widget);
            //rv.setRemoteAdapter(appWidgetIds[i], R.id.tvWidgetText1, intent);
            //rv.set

            // The empty view is displayed when the collection has no items. It should be a sibling
            // of the collection view.
            //rv.setEmptyView(R.id.stack_view, R.id.empty_view);
            

			

			//load preferences
			//Boolean noneAlternative = AppWidgetConfigure.loadNoneAlternative(context, appWidgetId);
			
			String[] parameters = AppWidgetConfigure.getParameters(context, appWidgetId);
			Log.d("_TextMissed_a1_", "Widget updateWidget olo1: "+parameters[2]+" noneAlternative: "+parameters[0]);
			
			Boolean noneAlternative = Boolean.parseBoolean(parameters[0]);
			
			//views.setViewVisibility(R.id.tvWidgetText2, View.GONE); //View.VISIBLE
			//views.setViewVisibility(R.id.tvWidgetText3, View.GONE); //View.VISIBLE
			//views.setViewVisibility(R.id.tvWidgetText4, View.GONE); //View.VISIBLE
			
			//views.removeAllViews(R.id.tvWidgetText1);
						

			
			//Update layout
			if (noneAlternative) {
				views.setTextViewText(R.id.tvWidgetText2, findStringIdinArrayXML(myTextSMS, context));
				//views.setTextViewText(R.id.tvWidgetText4, findStringIdinArrayXML(myTextCall, context));
			} else {
				views.setTextViewText(R.id.tvWidgetText2, myTextSMS);
				//views.setTextViewText(R.id.tvWidgetText4, myTextCall);
			}
			
			
			//views.setTextColor(R.id.tvWidgetText1, 0x000000);
			
			//String text = context.getString(R.string.tvWidgetText1); 
			String text = myTextCall; 
            Paint  mPaint = new Paint();
            mPaint.setAntiAlias(true);
            mPaint.setTextSize(10);
            mPaint.setColor(0xffffffff);
            mPaint.setTypeface(Typeface.create(Typeface.SERIF, Typeface.BOLD));
            float w = mPaint.measureText(text, 0, text.length());
            int olo = (int) w;
            // Create an empty, mutable bitmap
			Bitmap bitmap = Bitmap.createBitmap(olo, 13+5, Bitmap.Config.ARGB_4444);
			// get a canvas to paint over the bitmap
			Canvas canvas = new Canvas(bitmap);
			bitmap.eraseColor(0);
			//canvas.drawText(context.getString(R.string.tvWidgetText1), 0,15, mPaint);			
			canvas.drawText(myTextCall, 0,15, mPaint);
			
			//views.setImageViewBitmap(R.id.tvWidgetText1, bitmap);


			
			
			//Save changes
			appWidgetManager.updateAppWidget(appWidgetId, views);
			
			Log.d("_TextMissed_a1_", "Widget updateWidget");

			
		}
	}
	
	//zamien string na id w tablicy strings.xml
	private String findStringIdinArrayXML(String find, Context context) {
		String smsNumber="";
		String nmbToFind = "number00"+find;
		if (Integer.parseInt(find) == 0)
			smsNumber = context.getString(context.getResources().getIdentifier(nmbToFind, "string", context.getPackageName()));
		else if (Integer.parseInt(find) > 0 && Integer.parseInt(find) < 10 )
			smsNumber = context.getString(context.getResources().getIdentifier(nmbToFind, "string", context.getPackageName()));
		else if (Integer.parseInt(find) >= 10 && Integer.parseInt(find) < 100 ){
			nmbToFind = "number0"+find;
			smsNumber = context.getString(context.getResources().getIdentifier(nmbToFind, "string", context.getPackageName()));
		}
		else 
			smsNumber = find;
		
		return smsNumber;
	}
	
	@Override
	public void onDisabled(Context context) {
		Log.d("_TextMissed_a1_", "++++++++++++++Widget onDisabled ");
		// TODO Auto-generated method stub
		super.onDisabled(context);
	}

	@Override
	public void onEnabled(Context context) {
		Log.d("_TextMissed_a1_", "++++++++++++++Widget onEnabled ");
		// TODO Auto-generated method stub
		super.onEnabled(context);
		
		//start service 
		context.startService(new Intent(context, MyService.class));
	}
    
    //showToast
    public void showToast(String text) {
        toast.setText(text);
        toast.show();
    }
}